######  MISE A JOUR DE LA BASES DE VULNERABILITE fermer socket 


import socket, sys, threading, time, os, urllib, string, csv, ftplib, urllib2, tarfile, subprocess
from subprocess import call
portList = []

#fname="Resultat.CSV"
#write = open("Resultat.csv","w")
BDD="formater.csv"
#ftpfile = open("FTPFILE.csv","w")
#httpfile= open("HTTPFILE.csv","w")
#httpsfile= open("HTTPSFILE.csv","w")
vulnscan = open("Scan_Vuln.csv","w")

def ScanPort(port):
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.settimeout(2)
	try:
		s.connect((ip_address,port))
		portList.append(port)
		s.close()
	except socket.error:
		s.close()


def Compare(filename,port):
	f1 = file(filename,"r")
	f2 = file('formater.csv','r')
	cd1 = csv.reader(f1, delimiter = ' ')
	cd2 = csv.reader(f2, delimiter = ' ')
	
	for c1_row in cd1:
		for c2_row in cd2:
			if c1_row[0] == c2_row[1] and c1_row[1] == c2_row[2]:
				print "Vulnerabiliter trouvee ecriture dans fichier"
				vulnscan.write("Vulnerabilite trouvee sur port " + str(port) + " : " + str(c2_row[1]) + " "  +str(c2_row[2]) + " http://www.exploit-db.com/exploits/" + str(c2_row[0]) + "\n")

def grab_banner(ip_address,port):
	try:
		if port == 21:
			s=socket.socket()
			s.connect((ip_address,port))
			banner = s.recv(1024)
		#	write.write(str(port) + "," + str(banner) + "\n")
			ftpfile = open("FTPFILE.csv","w")
			ftpfile.write(str(banner))
			ftpfile.close()
			
			ftpresult = open("FTPRESULT.csv","w")
			ftpfile = open("FTPFILE.csv","r")
			for lines in ftpfile:
				rpl1 = lines.replace("220 ", "")
				rpl2 = rpl1.replace("(", "")
				rpl3 = rpl2.replace(")", "")
				ftpresult.write(rpl3.upper())
			ftpresult.close()			
			Compare("FTPRESULT.csv",port)
			ftp = ftplib.FTP(ip_address)
			res = ftp.login()
			print "Tentative de connexion en anonymous : " + res
			vulnscan.write("Tentative de connexion en anonymous : " + res + "\n")
			ftp.quit()
			os.remove("FTPFILE.csv")
			os.remove("FTPRESULT.csv")	
		elif port == 22:
			s=socket.socket()
			s.connect((ip_address,port))
			banner = s.recv(1024)
		#	print (banner)
			sshfile = open("SSHRESULT.csv","w")
			rpl1 = banner.replace("SSH-2.0-", "")
			rpl2 = rpl1.replace("_", " ")
			sshfile.write(rpl2.upper())
			sshfile.close()
			Compare("SSHRESULT.csv",port)
		#	os.remove("SSHRESULT.csv")
		elif port == 23:
			vulnscan.write("Port Telnet ouvert ... peut etre quelque chose d'interessant ici... \n")

		elif port == 80:
			httphd=urllib.urlopen(URL)
			infohttp = httphd.info().headers
		#	write.write(str(port) + "," + str(infohttp))
			httpfile = open("HTTPFILE.csv","w")
			httpfile.write(str(port) + "," + str(infohttp).upper())
			httpfile.close()

			httpfile = open("HTTPFILE.csv","r")
			formathttp = open("resultatHTTP.csv","w")

			reader = csv.reader(httpfile)
			for row in reader:
				formathttp.write(row[3] + "," + row[4])
			httpfile.close()
			
			formathttp.close()

			rechhttp = open("Seekhttp.csv","w")
			formathttp = open("resultatHTTP.csv","r")
			for lines in formathttp:
				rechhttp.write(lines.replace(' ' , ','))
			rechhttp.close()
			formathttp.close()
			
			httpresult = open("HTTPRESULT.csv","w")
			rechhttp = open("Seekhttp.csv","r")
			phpresult = open("PHPRESULT.csv","w")
			reader = csv.reader(rechhttp)
			for row in reader:
				finalhttp = row[2].replace("/", " ")
				httpresult.write(finalhttp)
				php = row[7].replace("/", " ")
				php1 = php.replace("-"," ")
				phpresult.write(php1)
			os.remove("HTTPFILE.csv")
			os.remove("Seekhttp.csv")
			os.remove("resultatHTTP.csv")
			phpresult.close()
			
			httpresult.close()

			Compare("HTTPRESULT.csv",port)
			Compare("PHPRESULT.csv",port)
			os.remove("HTTPRESULT.csv")
			os.remove("PHPRESULT.csv")

		elif port == 53:
			dnsfile = open("DNSFILE.csv","w")
			output = subprocess.Popen(["nslookup","-q=txt","-class=CHAOS","version.bind",ip_address], stdout=subprocess.PIPE).communicate()[0]
			
			dnsfile.write(output)
			dnsfile.close()
			
			
			file = open("DNSFILE.csv","r")
			formatdns = open("DNSFORMAT.csv","w")
			for line in file:
				if 'version.bind' in line:
					formatdns.write(line)
			file.close()
			formatdns.close()
			afile = open("DNSFORMAT.csv","r")
			dnsfile = open("DNSAV.csv","w")
			reader = csv.reader(afile, delimiter = '"')
			for row in reader:
				dnsfile.write(row[1])
			
			dnsfile.close()
			Compare("DNSAV.csv",port)
			os.remove("DNSFILE.csv")
			
			os.remove("DNSFORMAT.csv")
				
		elif port == 443:
			httphd=urllib.urlopen(URLS)
			infohttp = httphd.info().headers
		#	write.write(str(port) + ","  + str(infohttp))
			
			httpshd = open("HTTPSFILE.csv","w")
			httpshd.write(str(infohttp).upper())
			httpshd.close()
			
			httpshd = open("HTTPSFILE.csv","r")
			reader = csv.reader(httpshd)
			formathttps = open("resultatHTTPS.csv","w")
			for row in reader:
				formathttps.write(row[2] + "," + row[3])
			formathttps.close()

			rechhttps = open("Seekhttps.csv","w")
			formathttps = open("resultatHTTPS.csv","r")
			for lines in formathttps:
				rechhttps.write(lines.replace(' ', ','))
			rechhttps.close()
			formathttps.close()
			rechhttps = open("Seekhttps.csv","r")
			httpsresult = open("HTTPSRESULT.csv","w")
			reader = csv.reader(rechhttps)
			for row in reader:
				#print row[2].replace("/", " ")
				#httpsbuf = row[2].replace("/", " ")
				httpsresult.write(httpsbuf)
			os.remove("HTTPSFILES.csv")
			httpsresult.close()
			seekhttps.close()
			os.remove("Seekhttps.csv")
			Compare("HTTPSRESULT.csv",port)
			os.remove("HTTPSRESULT.csv")

			
			
		else:
			s=socket.socket()
			s.connect((ip_address,port))
			banner = s.recv(1024)
			write.write(str(port) + "," + str(banner) + "\n")
			s.close()
	except:
		return

if len(sys.argv) == 1:
	print "Argument necessaires"
	print "Pour avoir la liste des arguments taper : python start.py -h"
	sys.exit(1)


elif sys.argv[1] == "-u":
	print "Upgrade ..."
	urllib.urlretrieve("http://www.exploit-db.com/archive.tar.bz2","archive.tar.bz2")
	print "Telechargement termine"
	print "Recuperation et formatage de la base de donne en cours"
	FichierTAR = 'archive.tar.bz2'
	TAR = tarfile.open(FichierTAR)
	if tarfile.is_tarfile(FichierTAR):
		TAR.extract("files.csv")
	os.remove("archive.tar.bz2")
	call(["chmod","777","files.csv"])
	file = open("files.csv","r")
	write = open("formater.csv","w")
	reader = csv.reader(file)
	for row in reader:
		write.write(row[0] + " " + row[2].upper() + "\n")
#	write.close()
	file.close()
	os.remove("files.csv")

elif os.path.isfile(BDD) == False:
	print "Acun fichier de base de donnee trouvee"
	print "Pour telecharger la base de donnee mise a jour taper : python start.py -u "

elif sys.argv[1] == "-h":
	print "Scanner de vulnerailite :"
	print "Usage : python start.py X.X.X.X"
	print "-u : mise a jour de la base de donnee de vulnerabilite"
	print "-h : affiche cette aide"
	print "Programme cree par Jean-Yves Nazaire, Kilian Lavieille, Benjamin Berthelot"

	





else:
	print('Entrez adresse IP ou nom de domaine')
	ip_address=sys.argv[1]
	portdebut=int(input('Entrer port de debut: \n'))
	portfin=int(input('Entrer port de fin\n'))

	URL="http://" + ip_address
	URLS="https://" + ip_address
	while (portdebut != portfin):
    		portdebut= portdebut + 1
    		ScanPort(portdebut)
	print('FIN SCAN')
	for port in portList:
		grab_banner(ip_address,port)
#	write.close()

	#os.remove("DNSFORMAT.csv")
	#os.remove("resultatHTTP.csv")
	#os.remove("FTPFILE.csv")
	#os.remove("Seekhttp.csv")

